<template>
	<simple-layout
		class="ocip-select-people-box"
		:isUseCheck="false"
		:inputSearch="inputSearch"
		:isUseTopSlot="true"
		@toSearch="onSearch"
		@toBlur="onBlur"
	>
		<template #topLeft>
			<a-select
					v-model="selectValue"
					class="heade-left-box"
					@change="onSelectChange"
				>
					<a-select-option
						v-for="item in selectOptions"
						:value="item.id"
						:key="item.id">
						{{ item.name }}
					</a-select-option>
			</a-select>
		</template>
		<template #content>
			<top-bottom-layout
				ref="topBottomLayout"
				:is-show-down="isShowDown"
				:hidden-bottom="hiddenBottom"
			>
				<template #top>
					<div class="tree-root-box" :style="treeLabel" v-if="viewLabel">
						<span>

							<icon-font type="cap-icon-alternative-company" style="font-size: 16px; margin-left: 6px"/>
						</span>
						<span class="item-label">{{ viewLabel }}</span>
					</div>
					<a-ztree
						class="transfer-tree-box a-tree-custom-style"
						v-if="treeData.length > 0"
						:checkedKeys="checkedKeys"
						:check-strictly="true"
						:checkable="true"
						:showIcon="true"
						:selected-keys="selectedKeys"
						:loadData="onLoadData"
						:tree-data="treeData"
						:icon="renderIcon"
						:title="renderTitle"
						:replaceFields="replaceFields"
						@check="onCheck"
						@select="onSelect"
					>
					</a-ztree>
				</template>
				<template #middle>
					<a-radio :checked="true">{{ $i18n('org.member.label') }}</a-radio>
				</template>
				<template #bottom>
					<scroll-list
						panel="OcipOrganization"
						:command="searchValue ? 'search' : 'memberList'"
						ref="scrollList"
						:firstLoadSearch="firstLoadSearch"
						:showOtherProp="true"
						:otherProps="memberOtherProps"
					>
					</scroll-list>
				</template>
			</top-bottom-layout>
		</template>
	</simple-layout>
</template>

<script>
import SimpleLayout from '@/components/simpleLayout.vue';
import topBottomLayout from '@/components/topBottomLayout.vue';
import scrollList from '@/components/scrollList';

import {mapActions, mapState} from 'vuex';

import {getPanelData} from '@/api/modules/SelectOrgApi';
import {EntityTypes} from '@/utils/orgConstants';
import Bridge from '@/utils/Bridge';
import {CheckUtils} from '@/utils/checkUtils';
import {ACTION_REMOVE_ENTITY} from '@/store/actionTypes';
import {BtnType, Dialog} from '@/components/dialog';
import { TreeUtils } from '@/utils/treeUtils';
import seletOrgIconConfig from '../../config/iconfont';
import {MaskAsync} from '@/utils/Mask.js';

export default {
	name: 'OcipOrganization',
	components: {
		SimpleLayout,
		topBottomLayout,
		scrollList
	},
	inject: ['app'],
	data() {
		return {
			inputSearch: {
				placeText: $i18n('selectPeople.input',`${$i18n('common.company.label')}/${$i18n('org.member.label')}`)
			},
			searchValue: '',
			selectValue: '',
			selectOptions: [],

			treeData: [],
			replaceFields: {
				title: 'name',
				key: 'id'
				// children: 'children',
				// isLeaf: 'isLeaf'
			},
			expandedKeys: [],
			selectedKeys: [],
			checkedList: [],

			firstLoadSearch: false,
			// memberOtherProps: ['post'],

			checkNodeData: {
				checkeds: [],
				ids: []
			},
			nodeName: '',

			// 当前单位及部门数据集合
			unitIds: [],
			// 有子部门的部门是否被勾选状态，默认：没勾选
			unitsChecked: false,
			// 点击复选框时其勾选状态
			checkNodeStatus: false,
			isShowDown: false,
			hiddenBottom: false
		};
	},
	computed: {
		...mapState('selectData', ['selectedEntityMap']),
		orgSelect() {
			return this.app().orgSelect;
		},
		viewLabel() {
			if (this.selectValue) {
				let index = this.selectOptions.findIndex(
					(el) => el.id === this.selectValue
				);
				return this.selectOptions[index].name;
			} else {
				return '';
			}
		},
		checkedKeys: {
			set() {
			},
			get() {
				return this.checkedList;
			}
		},
		needDepartments() {
			let selectType = this.orgSelect.selectType;
			if (selectType.includes('Department') || selectType.includes('Member')) {
				return true;
			} else {
				return false;
			}
		},
		memberOtherProps() {
			return this.onSetOtherProps(['post']);
		}
	},
	watch: {
		selectedEntityMap: {
			deep: true,
			handler(val) {
				this.onSelectMap(val);
			}
		}
	},
	methods: {
		...mapActions('selectData', [ACTION_REMOVE_ENTITY]),
		onSearchData(data) {
			this.$refs.scrollList.search(data);
			if (this.orgSelect.selectType.indexOf(EntityTypes.Member) > -1) {
				// 可以选择人员时，则显示区域2
				this.isShowDown = false;
				this.hiddenBottom = false;
			}
		},
		async onGetTreeData(data) {
			let {
				onlyCurrentDepartment,
				showDepartmentsOfTree,
				showDepartmentsNoChildrenOfTree,
				showChild
			} = this.orgSelect;
			let pramas = {
				panel: 'OcipOrganization',
				command: 'childNodes',

				arguments: {
					needDepartments: this.needDepartments,
					onlyCurrentDepartment,
					showDepartmentsOfTree,
					showDepartmentsNoChildrenOfTree,
					showChild,
					...data
				}
			};
			let res = await getPanelData(pramas);
			if (res.code === 0) {
				let newTreeData = TreeUtils.resetTreeData(res.data);
				this.treeData = newTreeData;
			}
		},
		/**
		 * 切换视图
		 */
		onSelectChange(val) {
			this.onGetTreeData({ viewId: val });
		},

		async onGetSelect() {
			// ocip查询根视图使用的是loginAccountId
			let accountId = this.orgSelect.loginAccountId;
			let res = await getPanelData({
				panel: 'OcipOrganization',
				command: 'viewList',
				arguments: { accountId: accountId }
			});
			if (res.code === 0) {
				if (res.data.length < 1) {
					await Bridge.alert('未查询到可用视图，请联系管理员!');
					return;
				}
				this.selectOptions = res.data;
				this.selectValue = this.selectOptions[0].id;
				await this.onGetTreeData({ viewId: this.selectValue });
			}
		},
		/**
		 * 懒加载树形数据
		 */
		onLoadData(treeNode) {
			let viewId = treeNode.data.data.viewId;
			return new Promise((resolve) => {
				this.onAddTreeData(viewId).then(newData => {
					resolve(newData);
				});
			});
		},
		async onAddTreeData(id) {
			let params = {
				panel: 'OcipOrganization',
				command: 'childNodes',
				arguments: {
					viewId: id,
					needDepartments: this.needDepartments
				}
			};
			let res = await getPanelData(params);
			if (res.code === 0) {
				let newTreeData = TreeUtils.resetTreeData(res.data);
				return newTreeData;
			}
			return [];
		},
		/**
		 * 选中树节点
		 */
		onSelect(keys, selectData) {
			console.log('onSelect===>selectData', selectData);
			let data = selectData.node.data;
			let id = data.id;
			if (id.length === 0) {
				return;
			}
			let searchType = this.onSetSearchType()
			let type = data.type;
			this.selectedKeys = [id];
			if (type === 'Department') {
				let isOcipUnit = data.data.description === 'ocip_entity';
				this.firstLoadSearch = true;
				let params = this.onMemberListArguments();
				this.$nextTick(() => {
					this.onSearchData({
						...params,
						departmentId: id,
						keyword: this.searchValue,
						isOcipUnit: isOcipUnit,
						viewId: this.selectValue,
						searchType: searchType
					});
				});
			}
		},
		onSetSearchType() {
			let isAccount = this.orgSelect.selectType.includes(EntityTypes.Account);
			let isDepartment = this.orgSelect.selectType.includes(EntityTypes.Department);
			let isMember = this.orgSelect.selectType.includes(EntityTypes.Member);
			let searchType = `${isAccount ? 'Account,' : ''}${
				isDepartment ? 'Department,' : ''
			}${isMember ? 'Member' : ''}`;
			return searchType
		},
		/**
		 * 搜索回调
		 */
		onSearch(val) {
			this.searchValue = val;
			// searchType根据selectType判断
			let searchType = this.onSetSearchType()
			this.$nextTick(() => {
				// 搜索单位、人员
				if (val) {
					this.onSearchData({
						viewId: this.selectValue,
						keyword: val,
						searchType: searchType
					});
				} else {
					this.$refs.scrollList.initProps();
				}
			});
		},

		onCheck(keys, callbackData) {
			this.checkedList = keys;
			let nodeData = callbackData.node.data;
			let checkeds = [nodeData];
			let index = this.checkedKeys.findIndex(el => el === nodeData.id);
			if (index !== -1) {
				this.checkedList.splice(index, 1);
			}
			let node = {...nodeData, checked: !callbackData.checked};
			this.onDeptCheckDialog(
				{
					checkeds: checkeds,
					ids: JSON.parse(JSON.stringify(keys))
				},
				node
			);
		},
		/** 场景： 选择单位、部门（无子部门）做检查范围处理，部门（有子部门）时需要提示是否包含子部门弹窗，取消部门（有子部门）时不弹窗
		 * 1：如果是部门并且有子部门弹窗提示, 再次点击已勾选的部门（有子部门），取消当前部门，不弹出提示取消包含子部门
		 * 2：如果是单位、单个部门直接走检查范围
		 */
		@MaskAsync
		async onDeptCheckDialog(nodeData, nodeEl) {
			this.checkNodeData = nodeData;
			this.checkNodeStatus = nodeEl.checked;
			let activeCheckNode = nodeData.checkeds[0];
			let nodeList = [activeCheckNode.data];
			let nodeType = activeCheckNode.type;
			let notIncludeSubDept = [];

			// 已勾选直接取消勾选
			if (this.checkNodeStatus) {
				// 如果【已勾选】
				this[ACTION_REMOVE_ENTITY]({ entities: nodeList });
				return;
			}

			// 单选处理
			if (this.maxSize === '1') {
				this.onCheckScopeStatus([activeCheckNode.data]);
				return;
			}

			// 选择部门判断-点击的复选框有子部门，如果是部门有子节点，则有弹窗，否则直接勾选
			if (
				nodeType === 'Department' &&
				activeCheckNode.children &&
				activeCheckNode.children.length > 0
			) {
				let btnType = BtnType.OK;
				btnType = await Dialog.confirm({
					msg: `"${activeCheckNode.name}"是否包含子部门?`,
					okText: '包含',
					cancelText: '不包含'
				});
				if (btnType === BtnType.CLOSE) {
					return;
				}
				if (btnType === BtnType.CANCEL) {
					notIncludeSubDept.push(activeCheckNode.id);
				}
			}
			// 勾选单位，部门（无子部门）
			let checkContext = {
				currentPanel: 'OcipOrganization',
				notIncludeSubDept
			};
			let result = await CheckUtils.doCheckEntity(activeCheckNode, checkContext);
			if (!result) {
				return;
			}
			this.selectDataToRight(nodeList, notIncludeSubDept);
		},
		onSelectMap(val) {
			let pathKeys = val && Object.keys(val);
			if (pathKeys && pathKeys.length) {
				this.onTreeNodeAccount(val);
			} else {
				this.checkedList = [];
			}
		},
		onTreeNodeAccount(data) {
			this.checkedList = [];
			let typeIds = Object.keys(data);
			for (let item of typeIds) {
				if (
					item.indexOf('Account') !== -1 ||
					item.indexOf('Department') !== -1
				) {
					this.checkedList.push(item.split('|')[1]);
				}
			}
		},
		onMemberListArguments() {
			let {
				accessFileSecretLevel,
				isNeedCheckLevelScope,
				showConcurrentMember
			} = this.orgSelect;
			return {
				accessFileSecretLevel,
				isNeedCheckLevelScope,
				showConcurrentMember
			};
		},
		onBlur(val) {
			this.searchValue = val;
		},
		async onCheckScopeStatus(nodes) {
			let entity = nodes[0];
			let notIncludeSubDept = [];
			let checkContext = {
				currentPanel: 'OcipOrganization',
				notIncludeSubDept
			};
			let result = await CheckUtils.doCheckEntity(entity, checkContext);
			if (!result) {
				return;
			}
			await this.selectDataToRight(nodes);
		},
		onAccountIncludeTreeNode(nodes) {
			for (let i = 0; i < nodes.length; i++) {
				if (String(nodes[i].orgType) !== '3') {
					this.unitIds.push(nodes[i]);
				}
				if (nodes[i].children && nodes[i].children.length > 0) {
					this.onAccountIncludeTreeNode(nodes[i].children);
				}
			}
		},
		renderIcon(treeNode) {
			let { data } = treeNode;
			let type = data.type;
			// 单位icon
			let accountIcon = seletOrgIconConfig.seletOrgIconPath['cap-icon-alternative-company'];
			// 部门icon
			let departmentIcon = seletOrgIconConfig.seletOrgIconPath['cap-icon-alternative-department'];
			if (type === EntityTypes.Account) {
				return accountIcon;
			} else {
				return departmentIcon;
			}
		},
		/**
		 * 人员【密级】展示处理
		 * @param {Array} list 默认展示的人员信息
		*/
		onSetOtherProps(list) {
			if (this.orgSelect.showSecretLevel) {
				list.unshift('secretLevel')
			}
			return list
		}
	},
	created() {
		this.onGetSelect();
		this.onSelectMap(this.selectMap);
		if (
			this.orgSelect.rootAccountId === this.orgSelect.defaultAccountId ||
			this.orgSelect.rootAccountId === this.app().switchAfterUnit.id
		) {
			this.hiddenBottom = true;
		}
		if (!this.orgSelect.selectType.includes(EntityTypes.Member)) {
			this.hiddenBottom = true;
		}
	},
	mounted() {
		let ocipDepartment = {};
		let index;
		if (this.orgSelect.checkConfigEnums.length) {
			index = this.orgSelect.checkConfigEnums.findIndex(
				(item) => item.name === 'Department'
			);
			if (index !== -1) {
				ocipDepartment = {
					...this.orgSelect.checkConfigEnums[index],
					name: 'ocipDepartment'
				};
			}
			this.app().orgSelect.checkConfigEnums.push(ocipDepartment);
		}
	}
};
</script>
<style scoped lang="scss">

.ocip-select-people-box {
	.transfer-tree-box {
		padding: 6px 0 0 14px;
	}
	.tree-root-box {
		margin-top: 8px;
		padding-left: 15px;
		cursor: pointer;
		.item-label {
			margin-left: 6px;
			color: $defaultFontColor;
		}
	}
	.tree-node-line-box {
		flex: 1;
		@include flexCommon();

		.tree-node-line-box-icon {
			@include flexCommon();
			align-items: center;
			justify-content: center;
		}
	}
}

</style>
